package br.com.sovi.mobile.resources.ponto;

import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONException;
import org.openinsula.vulcano.core.command.invoker.CommandInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Path("/p")
@Produces(MediaType.TEXT_PLAIN)
public class PontoResource {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private CommandInvoker commandInvoker;

	@POST
	@Path("/post/add")
	public Object addPointPost(@FormParam("d") final String serial, @FormParam("ps") final List<PontoVO> pontos)
			throws JSONException {
		return addPoint(serial, pontos);
	}

	@GET
	@Path("/get/add")
	public Object addPointGet(@QueryParam("d") final String serial, @QueryParam("ps") final List<PontoVO> pontos)
			throws JSONException {
		return addPoint(serial, pontos);
	}

	private Object addPoint(final String serial, final List<PontoVO> pontos) {
		logger.debug("Gravando novo ponto.");
		logger.debug("Serial do Dispositivo: " + serial);
		logger.debug("Pontos recebidos: " + pontos.size());

		try {
			commandInvoker.invoke(new RecordPointCommand(serial, pontos));
			Boolean isInsideCerca = commandInvoker.invoke(new VerifyInsideCercaCommand(serial));
			String result = isInsideCerca ? "true" : "false";
			logger.debug("Resultado: " + result);
			return result;
		}
		catch (Exception e) {
			return "erro:" + e.getMessage();
		}
	}

}
